package com.raymond.cmpp.common.codec;



import com.raymond.cmpp.common.constance.GlobalConstance;
import com.raymond.cmpp.common.msg.BaseAgreement;
import com.raymond.cmpp.common.msg.MsgHead;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 协议解码
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-08-05 11:42
 */
public class AgreementDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf bytebuf, List<Object> out) throws Exception {
        out.add(byteBuf2BaseAgreement(bytebuf));
    }

    public static BaseAgreement byteBuf2BaseAgreement(ByteBuf bytebuf) {
        BaseAgreement baseAgreement = new BaseAgreement();
        baseAgreement.setTotalLength(bytebuf.readInt());
        baseAgreement.setCommandId(bytebuf.readInt());
        baseAgreement.setSequenceId(bytebuf.readInt());
        baseAgreement.setHeadLength(MsgHead.getHeadLength());
        baseAgreement.setBodyLength(baseAgreement.getTotalLength() - baseAgreement.getHeadLength());
        if (baseAgreement.getBodyLength() > 0) {
            baseAgreement.setBodyBuffer(new byte[baseAgreement.getBodyLength()]);
            assert(baseAgreement.getBodyLength() == bytebuf.readableBytes());
            bytebuf.readBytes(baseAgreement.getBodyBuffer());
        } else {
            baseAgreement.setBodyBuffer(GlobalConstance.EMPTY_BYTES);
        }
//        System.out.println("CommandId:" + baseAgreement.getCommandId());
        return baseAgreement;
    }

}
